#coding:utf-8
from django.db.models.signals import post_save
from django.dispatch import receiver
import logging

from goods_info.models import GoodsModel, GoodsInventoryModel
from  .models import WarehouseModel

@receiver(post_save,sender=WarehouseModel)#sender是谁发送的，post_save新增保存是触发,receiver接收信号
def create_goods_inventory(sender,instance,created,**kwargs): #instance传入的对象
    """
    创建信号监控函数，信号接收者收到之后自动触发。创建菜单资源对应的权限
    创建新仓库之后，给所有的货品在当前的新仓库，新增库存数据
    """
    if created:
        logging.info('创建当前新仓库的所有库存数据')
        if isinstance(instance,WarehouseModel):
            #查询所有货品的ID数据
            ids=GoodsModel.objects.values_list('id',flat=True).all()
            #批量插入库存记录数据
            inventory_list=[]
            for goods_id in ids:
                inventory_list.append(
                    GoodsInventoryModel(goods_id=goods_id,
                                        warehouse_id=instance.id,
                                        warehouse_name=instance.name)
                )
            #批量新增函数：bulk_create
            GoodsInventoryModel.objects.bulk_create(inventory_list)
        else:
            logging.info('不需要创建库存数据')











































